﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProductKeyManager.DB;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using System.Globalization;

namespace ProductKeyManager.Xml
{
    /// <summary>
    /// XML Handler for the MSDN format key file.
    /// </summary>
    public class MsdnXmlHandler: IXmlHandler
    {
        #region IXmlHandler Members

        private List<Product> _Products;

        /// <summary>
        /// Gets the products imported from the XML.
        /// </summary>
        /// <value>The products.</value>
        public IEnumerable<Product> Products
        {
            get { return _Products; }
        }

        /// <summary>
        /// Imports the XML.
        /// </summary>
        /// <param name="fileUri">The file URI.</param>
        /// <returns></returns>
        public void ImportXml(Uri fileUri)
        {
            List<string> names = new List<string>();
            _Products = new List<Product>();
            XmlReader reader = XmlReader.Create(fileUri.ToString());

            while (reader.ReadToFollowing("Product_Key"))
            {
                Product newProduct = null;

                if (reader.GetAttribute("Name") != null && reader.GetAttribute("Key") != null)
                {
                    string allocatedTo = reader.GetAttribute("AllocatedTo");
                    if (allocatedTo == null)
                    {
                        allocatedTo = "Not Allocated";
                    }

                    if (names.Contains(reader.GetAttribute("Name")))
                    {
                        Key newKey = new Key
                        {
                            Code = reader.GetAttribute("Key"),
                            AllocatedTo = allocatedTo
                        };
                        _Products[names.IndexOf(reader.GetAttribute("Name"))].Keys.Add(newKey);
                    }
                    else
                    {
                        newProduct = new Product
                        {
                            Name = reader.GetAttribute("Name")
                        };

                        Key newKey = new Key
                        {
                            Code = reader.GetAttribute("Key"),
                            AllocatedTo = allocatedTo
                        };

                        newProduct.Keys.Add(newKey);

                        _Products.Add(newProduct);

                        names.Add(newProduct.Name);
                    }
                }
            }
        }

        private string _GeneratedXml;

        /// <summary>
        /// Gets the XML generated by from the products.
        /// </summary>
        /// <value>The generated XML.</value>
        public string GeneratedXml
        {
            get { return _GeneratedXml; }
        }

        /// <summary>
        /// Generates the XML.
        /// </summary>
        /// <param name="products">The products.</param>
        /// <returns></returns>
        public void GenerateXml(IEnumerable<Product> products)
        {
            GenerateXml(products, false, ""); 
        }

        /// <summary>
        /// Generates the XML.
        /// </summary>
        /// <param name="products">The products.</param>
        /// <param name="generateStyleSheet">if set to <c>true</c> the stylesheet is generated.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public void GenerateXml(IEnumerable<Product> products, bool generateStyleSheet, string fileName)
        {
            string xmlResult = "<?xml version=\"1.0\" standalone=\"yes\" ?>" + Environment.NewLine;
            if (generateStyleSheet && !String.IsNullOrEmpty(fileName))
            {
                xmlResult += "<?xml-stylesheet type=\"text/xsl\" href=\"" + fileName + ".xsl\"?>" + Environment.NewLine;
            }
            List<XElement> elements = new List<XElement>();

            foreach (Product prod in products)
            {
                foreach (Key key in prod.Keys)
                {
                    XElement element = new XElement("Product_Key",
                                               new XAttribute("Name", prod.Name),
                                               new XAttribute("Key", key.Code),
                                               new XAttribute("AllocatedTo", key.AllocatedTo));
                    elements.Add(element);
                }
            }

            XElement xml = new XElement("Your_Product_Keys", elements.ToArray());

            _GeneratedXml = xmlResult + xml.ToString();
        }

        #endregion
    }
}
